import { getPcitureCode, getPhoneCode, getUserInfo, login } from "../../service/index.js"

Page({
    data: {
        verificationCode: '',
        verificationKey: '',
        verificationCodeInput: '1111',
        msgCodeInput: '246810',
        phoneNumber: '18917286702',
        msgButtonShowText: '发送短信',
        msgButtonDisabled: false,
        countDown: 60 // 倒计时时间（秒）
    },

    onLoad(options) {
        this.getVerificationCode()
    },

    getVerificationCode: function () {
        getPcitureCode(
            (res) => {
                this.setData({
                    verificationCode: res.data.base64,
                    verificationKey: res.data.key
                });
            },
            (fail) => {
                wx.showToast({ title: '获取图形验证码失败', icon: 'none' })
            }
        );
    },

    sendCode: function () {
        if (this.data.phoneNumber.length !== 11) {
            wx.showToast({ title: '请输入11位手机号码', icon: 'none' })
            return;
        }
        if (this.data.verificationCodeInput === '') {
            wx.showToast({ title: '请输入图形验证码', icon: 'none' })
            return
        }
        getPhoneCode(this.data.verificationCodeInput, this.data.verificationKey, this.data.phoneNumber,
            (res) => {
              wx.showToast({ title: '验证码已发送', icon: 'success' })
             console.log(res);
             // 启动倒计时
             this.startCountDown();
            },
            (fail) => {
                wx.showToast({ title: '获取验证码失败', icon: 'none' })
            }
        )
    },
    startCountDown: function () {
      this.setData({
          msgButtonDisabled: true,
          msgButtonShowText: `重新发送${this.data.countDown}）`
      });

      const interval = setInterval(() => {
          const newCountDown = this.data.countDown - 1;

          if (newCountDown <= 0) {
              clearInterval(interval);
              this.setData({
                  msgButtonShowText: '发送短信',
                  msgButtonDisabled: false,
                  countDown: 60 // 重置倒计时时间
              });
          } else {
              this.setData({
                  countDown: newCountDown,
                  msgButtonShowText: `重新发送（${newCountDown}）`
              });
          }
      }, 1000); // 每秒更新一次
    },
    toLogin: function () {
        if (this.data.phoneNumber.length !== 11) {
            wx.showToast({ title: '请输入11位手机号码', icon: 'none' });
            return
        }
        if (this.data.msgCodeInput === '') {
            wx.showToast({ title: '请输入短信验证码', icon: 'none' })
            return
        }
        login(this.data.phoneNumber, this.data.msgCodeInput, (res) => {
            if(res.status===500){
              wx.showToast({ title: '登录失败', icon: 'success' })
              return
            }
            wx.showToast({ title: '登录成功', icon: 'success' })
            // 保存手机号到本地存储
            wx.setStorageSync('phoneNumber', this.data.phoneNumber);
            // 保存Token到本地存储
            wx.setStorageSync('token', res.data.token);
            //获取用户登录信息
            getUserInfo( (res) => {
              wx.setStorageSync('user', res.data.userInfo);
            })
            // 使用 setTimeout 延迟跳转，确保提示框显示
            setTimeout(() => {
              // 登录成功后跳转到首页
              wx.switchTab({
                  url: '/pages/my/index', // 确保路径是相对于根目录的正确路径
                  success: function() {
                      console.log('跳转成功');
                  },
                  fail: function(err) {
                      console.log('跳转失败', err)
                  }
              });
          }, 1000); // 延迟 1.5 秒（根据需要调整延迟时间）

        }, (fail) => {
            wx.showToast({ title: '登录失败', icon: 'none' })
        });
    },

    observers: {
        'verificationCode': function (newValue) {
            console.log('验证码变化:', newValue);
        }
    },
});
